﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using KnowledgeCommunity.Model;
using KnowledgeCommunity.Service;
using KnowledgeCommunity.Web.Models;
using KnowledgeCommunity.Web.DbHelper;

namespace KnowledgeCommunity.Web.Controllers
{
    public class TroubleController : Controller
    {
        TroubleHelper myTroubleHelper = new TroubleHelper();
        AnswerHelper myAnswerHelper = new AnswerHelper();
        //
        // GET: /Trouble/

        public ActionResult Index()
        {
            var troubles = myTroubleHelper.FindAll();
            var answers = myAnswerHelper.FindAll();
            ViewData["TroubleList"] = troubles;
            ViewData["AnswerList"] = answers;
            return View();
        }

        public ActionResult List()
        {
            KnowledgeCommunity.Web.Models.Page Model = new Page();
            Model.CurrentPageIndex = 1;  //当前页 默认第一页

            int SkinCount = (Model.CurrentPageIndex - 1) * Model.PageSize;

            //测试用例。实际用自己的逻辑获取数据
            List<Trouble> datesource = GetDataSource();//要分页的数据源
            Model.TroubleList = datesource.Where(r => r.Id >= 0).Skip(SkinCount).Take(Model.PageSize).ToList();
            //测试用例。实际用自己的逻辑获取数据

            //是否开启Ajax分页
            Model.IsAjax = true;
            Model.TotalCount = datesource.Count;//获取记录总数

            //获取分页数据
            Model.TroubleList = datesource.Where(r => r.Id >= 0).Skip(SkinCount).Take(Model.PageSize).ToList();
            return View(Model);

        }

        private List<Trouble> GetDataSource()
        {
            var Trouble = myTroubleHelper.FindAll();
            List<Trouble> model = new List<Trouble>();
            foreach (var item in Trouble)
            {
                model.Add(item);
            }
            return model;
        }

        public ActionResult PageIndex(Models.Page Model)
        {

            //分页数据源。自己写逻辑获取。

            int SkinCount = (Model.CurrentPageIndex - 1) * Model.PageSize;

            //测试用例。实际用自己的逻辑获取数据
            List<Trouble> datesource = GetDataSource();//要分页的数据源
            Model.TroubleList = datesource.Where(r => r.Id >= 0).Skip(SkinCount).Take(Model.PageSize).ToList();
            //测试用例。实际用自己的逻辑获取数据

            Model.TotalCount = datesource.Count;//获取记录总数
            if (Request.IsAjaxRequest())  //是AJAX请求的话返回AJAX分页数据
            {
                Model.IsAjax = true;
                return View(Model);
            }
            else
            {
                Model.IsAjax = false;
                return this.PartialView("List", Model);
            }
            //return View(Model);
        }

        public ActionResult Details(int id)
        {
            var model = myTroubleHelper.FindById(id);
            var answers = myAnswerHelper.FindByCode(model.ShapeCode);
            ViewData["AnswerList"] = answers;
            return View(model);
        }

        public ActionResult AnswerCreate(Answer model) 
        {
            string cont = Request.Form["message"];
            string _id=Request.Form["Id"];
            
            string code = Request.Form["ShapeCode"];
            if (cont != "" && _id != "")
            {
                int Id = Convert.ToInt32(_id);
                model.Content = cont;
                model.ShapeCode = code;
                model.AddTime = DateTime.Now;
                model.UserName = HttpContext.User.Identity.Name;
                model.State = 0;
                bool n = myAnswerHelper.Create(model);
                if (n)
                {
                    var t1 = myTroubleHelper.FindById(Id);
                    t1.State=1;
                    DoUpdateModel(t1);
                    return RedirectToAction("Details", "Trouble", new { id = Id });
                }
                else
                {
                    return RedirectToAction("Error", "Notice", new { type = 1 });
                }
            }
            else 
            {
                return RedirectToAction("Index", "Trouble");
            }
        }

        [Authorize]
        public ActionResult Create()
        {
            return View();
        }

        [ValidateInput(false)]
        [Authorize]
        [HttpPost]
        public ActionResult Create(Trouble model)
        {
            string code = "TA" + RandomNumber.GenerateRandomNumber();
            if (code != null)
            {
                model.ShapeCode = code;
                model.UserName = HttpContext.User.Identity.Name;
                model.AddTime = DateTime.Now;
                model.State = 0;
                bool n = myTroubleHelper.Create(model);
                if (n)
                {
                    if (HttpContext.User.IsInRole("editor") || HttpContext.User.IsInRole("admin"))
                    {
                        return RedirectToAction("List", "Trouble");
                    }
                    else
                    {
                        return RedirectToAction("MyTrouble", "Zone");
                    }
                }
                else
                {
                    return RedirectToAction("Error", "Notice", new { type = 1 });
                }
            }
            else 
            {
                return RedirectToAction("Error", "Notice", new { type = 1 });
            }

        }

        [Authorize]
        public ActionResult Replay(int id) 
        {
            var model = myTroubleHelper.FindById(id);
            var ans = myAnswerHelper.FindByCode(model.ShapeCode);
            ViewData["AnswerList"] = ans;
            return View(model);
        }

        [ValidateInput(false)]
        [Authorize]
        [HttpPost]
        public ActionResult Replay()
        {
            Answer model = new Answer();
            string Id = Request.Form["Id"];
            string message=Request.Form["_message"];
            string code = Request.Form["ShapeCode"];
            if (message != "" && code != "")
            {
                model.Content = message;
                model.ShapeCode = code;
                myAnswerHelper.Create(model);
            }
            return RedirectToAction("Reqlay", "Trouble", new { id = Id });
        }

        [Authorize]
        public ActionResult Edit(int id)
        {
            var _Trouble = myTroubleHelper.FindById(id);
            return View(_Trouble);
        }

        [ValidateInput(false)]
        [Authorize]
        [HttpPost]
        public ActionResult Edit(Trouble model)
        {
            DoUpdateModel(model);
            return RedirectToAction("Details", new { id = model.Id });
        }

        [Authorize]
        public ActionResult Delete(int id)
        {
            var _Trouble = myTroubleHelper.FindById(id);
            return View(_Trouble);
        }

        [Authorize]
        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            bool n = myTroubleHelper.Delete(id);
            if (n)
                return List();
            else
                return RedirectToAction("Error", "Notice", new { type = 2 });
        }

        CKCDB mydb = new CKCDB();

        private void DoUpdateModel(Trouble model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var app = mydb.Troubles.Find(model.Id);
                    UpdateModel(app);
                    mydb.SaveChanges();
                }
                catch (Exception ex)
                {
                    string message = "Create in table<Troubles>" + ex.ToString();
                    WriteLog.WriteSysLog(message);
                }
            }
        }

    }
}
